package cn.xsly.ymcc.web.controller;

import cn.xsly.ymcc.dto.StocksDto;
import cn.xsly.ymcc.result.JSONResult;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/trolley")
public class QuartZController extends QuartzJobBean {
    private static final String SHOP_CART = "shop-cart:";
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public JSONResult save(@RequestBody StocksDto stocksDto) {
        stocksDto.setTime(new Date());
        String key = SHOP_CART + stocksDto.getUserId();
        String key1 = stocksDto.getGoodsId().toString();
        HashOperations hashOperations = redisTemplate.opsForHash();
        //Map<String, Map<String, String>> map = JSON.parseObject(JSONObject.toJSONString(stocksDto), Map.class);
        Map map = JSON.parseObject(JSONObject.toJSONString(stocksDto), Map.class);

        hashOperations.put(key, key1, map);

        return JSONResult.success(stocksDto);
    }

    @RequestMapping(value = "/query/{userId}", method = RequestMethod.GET)
    public JSONResult query(@PathVariable("userId") Long userId) {
        String key = SHOP_CART + userId;
        //通过key获取商品数据
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 把hash数据结构中的商品全部循环迭代出来
        for (Map.Entry<Object, Object> entry : entries.entrySet()) {
            resultList.add((Map<String, Object>) entry.getValue());
        }

        return JSONResult.success(resultList);
    }

    @RequestMapping(value = "/delete/{userId}/{goodsId}", method = RequestMethod.DELETE)
    public JSONResult delete(Long userId, Long goodsId) {
        String key = SHOP_CART + userId;
        redisTemplate.opsForHash().delete(key, goodsId.toString());
        return JSONResult.success();
    }

    @RequestMapping(value = "/delete/{userId}", method = RequestMethod.DELETE)
    public JSONResult deleteUser(Long userId) {
        String key = SHOP_CART + userId;
        this.redisTemplate.opsForHash().delete(key);
        return JSONResult.success();
    }

    //查所有用户以及购买的所有商品
    @GetMapping("/StationCharger")
    public JSONResult init() {
        Set<String> keys = redisTemplate.keys("shop-cart:*");
        List list = new ArrayList<>();
        for (String key : keys) {
            Map entries = this.redisTemplate.opsForHash().entries(key);
            System.out.println(entries);
            Map map = new HashMap<>();
            map.put("userId", keys);
            list.add(map);
        }
        return JSONResult.success();
    }

    @GetMapping("/test")
    public void test(){
        Set<String> keys = redisTemplate.keys("shop-cart:*");

        for (String key : keys) {
            Map<String, Object> entries = redisTemplate.opsForHash().entries(key);
            for (Map.Entry<String, Object> entry : entries.entrySet()) {
                Object value = entry.getValue();
                JSONObject jsonObject = new JSONObject((Map<String, Object>) value);
                String o = jsonObject.toString();
                StocksDto stocksDto = JSON.parseObject(o, StocksDto.class);
                if (System.currentTimeMillis() - stocksDto.getTime().getTime() > 2*60*1000) {
                    redisTemplate.opsForHash().delete(key, entry.getKey());
                }
            }
            //System.out.println("test");
        }
    }
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        Set<String> keys = redisTemplate.keys("shop-cart:*");

        for (String key : keys) {
            Map<String, Object> entries = redisTemplate.opsForHash().entries(key);
            for (Map.Entry<String, Object> entry : entries.entrySet()) {
                Object value = entry.getValue();
                JSONObject jsonObject = new JSONObject((Map<String, Object>) value);
                String o = jsonObject.toString();
                StocksDto stocksDto = JSON.parseObject(o, StocksDto.class);
                if (System.currentTimeMillis() - stocksDto.getTime().getTime() > 2*60*1000) {
                    redisTemplate.opsForHash().delete(key, entry.getKey());
                }
            }
            //System.out.println("test");
        }

    }
}
